package config

import (
	"os"
	"path/filepath"

	"github.com/toolkits/pkg/file"
	"gopkg.in/yaml.v3"
)

type database struct {
	Host     string `yaml:"host"`
	Type     string `yaml:"type"`
	Port     int    `yaml:"port"`
	Username string `yaml:"username"`
	Password string `yaml:"password"`
	Database string `yaml:"database"`
}

type Config struct {
	Version  string `yaml:"version"`
	LogLevel string `yaml:"log_level"`

	SourceDB database `yaml:"source_db"`
	TargetDB database `yaml:"target_db"`
}

func (c *Config) Save(path string) error {
	yamlFile, err := yaml.Marshal(c)
	if err != nil {
		return err
	}

	return os.WriteFile(path, yamlFile, 0644)
}

func NewConfig(path string) (*Config, error) {

	conf := &Config{
		Version:  "1.0.0",
		LogLevel: "info",
		SourceDB: database{
			Host:     "localhost",
			Type:     "mysql",
			Port:     3306,
			Username: "root",
			Password: "root",
			Database: "sourceDB",
		},
		TargetDB: database{
			Host:     "localhost",
			Type:     "mysql",
			Port:     3306,
			Username: "root",
			Password: "root",
			Database: "targetDB",
		},
	}

	confFilePath := filepath.Join(file.SelfDir(), "config.yaml")
	if err := conf.Save(confFilePath); err != nil {
		return nil, err
	}

	return conf, nil
}

func LoadConfig() (*Config, error) {
	confFilePath := filepath.Join(file.SelfDir(), "config.yaml")
	if !file.IsExist(confFilePath) {
		return NewConfig(confFilePath)
	}

	content, err := os.ReadFile(confFilePath)
	if err != nil {
		return NewConfig(confFilePath)
	}

	var config Config
	if err = yaml.Unmarshal(content, &config); err != nil {
		return nil, err
	}

	return &config, nil
}
